package leetcode;

import java.util.Stack;

/**
 * @author Liangyaoyun
 */
public class leetCode20 {
    public boolean isValid(String s) {
        char[] res = s.toCharArray();
        Stack<Character> stack = new Stack<Character>();
        boolean flag=false;
        if (res.length%2==1){
            return false;
        }
        for (int i = 0; i < res.length; i++) {
            if (res[i] == '(' || res[i] == '{' || res[i] == '[') {
                flag=true;
                stack.push(res[i]);
            } else if (res[i] == ')' || res[i] == '}' || res[i] == ']') {
                if (stack.isEmpty())return false;
                if (res[i] == ')') {
                    if (stack.peek()=='(') {
                        stack.pop();
                    }
                    else {
                        return false;
                    }
                } else if (res[i] == '}') {
                    if (stack.peek()=='{') {
                        stack.pop();
                    }else {
                        return false;
                    }
                }
                else if (res[i] == ']') {
                    if (stack.peek()=='[') {
                        stack.pop();
                    }
                    else {
                        return false;
                    }
            }
            }
        }
        if (stack.isEmpty()&&flag) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        String s = "()))";
        leetCode20 leetCode20 = new leetCode20();
        leetCode20.isValid(s);
    }
}
